package com.david.func_test

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

/**步数工具类*/
class StepUtil {
    private var mSensorManager: SensorManager? = null
    private var mStepsFromBoot = 0 // 自应用运行以来STEP_DETECTOR检测到的步数

    private var mStepsFromAppStart = 0 // 自系统开机以来STEP_COUNTER检测到的步数

    private var isRegister = false

    private var mListener: SensorEventListener? = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {
//            println("@@@:" + event.sensor.type + "--" + Sensor.TYPE_STEP_DETECTOR + "--" + Sensor.TYPE_STEP_COUNTER)
            if (event.sensor.type == Sensor.TYPE_STEP_DETECTOR) {//接收走了一步事件
                if (event.values[0] == 1.0f) {
                    ++mStepsFromAppStart
                }
            } else if (event.sensor.type == Sensor.TYPE_STEP_COUNTER) {//接收自开机以来步数
                mStepsFromBoot = event.values[0].toInt()
            }
//            val desc = String.format("设备检测到您当前走了%d步，自开机以来总数为%d步", mStepDetector, mStepCounter)
//            mStepTV?.setText(desc)
        }

        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
    }


    fun checkSupport(context: Context):Boolean{
        return isSupportStepCountSensor(context)
    }

    /**
     * 判断该设备是否支持计歩
     *
     * @param context
     * @return
     */
    fun isSupportStepCountSensor(context: Context): Boolean {
        setManager(context)

        val countSensor = mSensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        val detectorSensor = mSensorManager?.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR)
        return countSensor != null || detectorSensor != null
    }

    private fun setManager(context: Context){
        if (mSensorManager == null) {
            mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        }
    }

    /**
     * 检测权限，未授权时会申请权限,
     */
    fun checkPermission(activity: Activity):Boolean{
        return if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACTIVITY_RECOGNITION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                activity, arrayOf(Manifest.permission.ACTIVITY_RECOGNITION),
                1000
            )
            false
        } else {
            registerListener()
            true
        }
    }

    /**
     * 授权之后检测是否授权
     */
    fun checkPermissionResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray):Boolean{
        permissions.map {
            if (requestCode == 1000) {
                return if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    registerListener()
                    true
                } else {
                    false
                }
            }
        }
        return false
    }

    fun getStepsFromBoot(): Int{
        return mStepsFromBoot
    }
    fun getStepsFromAppStart(): Int{
        return mStepsFromAppStart
    }

    private fun registerListener(){
        if (!isRegister) {
            mSensorManager?.registerListener(
                mListener, mSensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR),
                SensorManager.SENSOR_DELAY_NORMAL
            )
            mSensorManager?.registerListener(
                mListener, mSensorManager!!.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                SensorManager.SENSOR_DELAY_NORMAL
            )
            isRegister = true
        }
    }

    /**
     * 步数显示页面退出之后调用
     */
    fun onDestroy(){
        if (isRegister)
            mSensorManager?.unregisterListener(mListener)
        mSensorManager = null
    }
}